package cn.wsh.system.service.impl;

import cn.wsh.system.domain.Role;
import cn.wsh.system.mapper.RoleMapper;
import cn.wsh.system.service.IRoleService;
import cn.wsh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wushenghua
 * @since 2022-02-20
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void add(Role role) {
        super.add(role);//返回自增id
        initRelationTable(role);
    }

    private void initRelationTable(Role role) {
        //1.移除原来的数据
        if(role.getId() != null){
            roleMapper.removeRoleMenu(role.getId());
            roleMapper.removeRolePermission(role.getId());
        }
        //2.都是新增
        if(role.getMenus() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("roleId", role.getId());
            map.put("menuIds",role.getMenus());
            roleMapper.batchSaveMenu(map);
        }
        if(role.getPermissions() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("roleId", role.getId());
            map.put("perIds",role.getPermissions());
            roleMapper.batchSavePermission(map);
        }
    }

    @Override
    public void update(Role role) {
        super.update(role);
        initRelationTable(role);

    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }

}
